package com.yanqu.road.server.manager.activity.unionchest;

import com.yanqu.road.entity.activity.unionChest.CrossUnionChestBoxData;
import com.yanqu.road.entity.activity.unionChest.config.UnionChestBoxConfig;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class CrossUnionChestInfo {
    private int activityId;
    private String unionId;
    private AtomicLong maxBoxId = new AtomicLong(1);
    private Map<Long, CrossUnionChestBoxData> boxDataMap = new ConcurrentHashMap<>();

    public CrossUnionChestInfo(int activityId, String unionId) {
        this.activityId = activityId;
        this.unionId = unionId;
    }

    public void initByDb(Map<Long, CrossUnionChestBoxData> tempBoxDataMap) {
        for (CrossUnionChestBoxData unionChestBoxData : tempBoxDataMap.values()) {
            boxDataMap.put(unionChestBoxData.getBoxId(), unionChestBoxData);

            if (unionChestBoxData.getBoxId() > maxBoxId.get()) {
                maxBoxId.set(unionChestBoxData.getBoxId());
            }
        }

    }

    public List<CrossUnionChestBoxData> getBoxDataList() {
        synchronized (boxDataMap) {
            List<CrossUnionChestBoxData> list = new ArrayList<>(boxDataMap.values());
            return list;
        }
    }

    private long newBoxId() {
        return maxBoxId.addAndGet(1);
    }

    public CrossUnionChestBoxData shareBox(long userId, UnionChestBoxConfig boxConfig) {
        CrossUnionChestBoxData crossUnionChestBoxData = new CrossUnionChestBoxData(activityId, unionId, newBoxId());
        crossUnionChestBoxData.setBoxType(boxConfig.getType());
        crossUnionChestBoxData.setShareUserId(userId);
        crossUnionChestBoxData.setShareTime(DateHelper.getCurrentTime());
//        for (int i = 0; i < boxConfig.getNum(); i++) {
//            UnionChestBoxInfo boxInfo = new UnionChestBoxInfo(i + 1);
//            crossUnionChestBoxData.addBoxInfo(boxInfo);
//        }
        boxDataMap.put(crossUnionChestBoxData.getBoxId(), crossUnionChestBoxData);
        return crossUnionChestBoxData;
    }

    public CrossUnionChestBoxData getBoxData(long boxId) {
        return boxDataMap.get(boxId);
    }
}
